package com.coder.baseapp.wrapper;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;

import java.util.Iterator;
import java.util.Stack;

/**
 * @Author: Tua.CoderGui
 * *
 * @Date: 2017/3/11
 * *
 * Copyright (c) 2017 All Rights Reserved.
 */
public class AppStack {

    private static AppStack ourInstance = null;

    // Activity栈
    private Stack<Activity> activityStack = new Stack<Activity>();

    private AppStack() {

    }

    public static synchronized AppStack getInstance() {
        if (ourInstance == null) {
            ourInstance = new AppStack();
        }
        return ourInstance;
    }

    /**
     * 添加Activity到堆栈
     */
    public void pushActivity(Activity activity) {
        activityStack.push(activity);
    }


    /**
     * 结束指定的Activity
     */
    public void popActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        Iterator<Activity> iterator = activityStack.iterator();
        while (iterator.hasNext()) {
            Activity activity = iterator.next();
            if (activity.getClass().equals(cls)) {
                popActivity(activity);
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        Iterator<Activity> iterator = activityStack.iterator();
        while (iterator.hasNext()) {
            popActivity(iterator.next());
        }
        activityStack.clear();
    }

    /**
     * 退出应用程序
     */
    public void AppExit(Context context) {
        try {
            finishAllActivity();
            ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            activityMgr.killBackgroundProcesses(context.getPackageName());
            System.exit(0);
        } catch (Exception e) {
        }
    }

    /**
     * App重启
     *
     * @param context
     */
    public void AppRestart(Context context) {
        Intent i = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
        AppExit(context);
    }
}
